﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web.core.ViewModels;
using web.core.Models;
using web.component;
using web.data.entities;
using System.IO;

namespace web.core.Controllers
{
    public class admSiteSettingController : baseController
    {
        #region structure - declare
        //constructure for site setting item
        private site_settings CreateItem(string key, string value, int lang_id, int isconfig)
        {
            var it = new site_settings()
            {
                setting_name = key,
                setting_content = value,
                date_modified = Udate_time.GetCurrentDateTime(),
                // setting_type = type, 
                language_id = (lang_id == -1 ? admin_const.DEFAULT_LANGUAGE_ID : lang_id),
                is_config = (isconfig != admin_const.DEFAULT_ITEM_STATUS ? 0 : admin_const.DEFAULT_ITEM_STATUS)
            };
            return it;
        }

        private SiteSettingEntities stnewEntities(string _key, string _desc, int _iptype, int _isconfig)
        {
            var it = new SiteSettingEntities()
            {
                key = _key,
                desc = _desc,
                setting_type = _iptype,
                value = "",
                is_config = (_isconfig != admin_const.DEFAULT_ITEM_STATUS ? 0 : admin_const.DEFAULT_ITEM_STATUS)
            };
            return it;
        }

        private List<SiteSettingEntities> ListCommonSetting()
        {
            return new List<SiteSettingEntities>(){
                    //page
                    stnewEntities(global_const.PAGE_NAME, "Tên trang", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.KEYWORD, "Meta Keyword", (int)admin_const.SETTING_TYPE.TEXT_AREA,1),
                    stnewEntities(global_const.DESCRIPTION, "Meta Description", (int)admin_const.SETTING_TYPE.TEXT_AREA,1),
                    stnewEntities(global_const.POWEREDBY, "Meta poweredBy", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.DCCREATOR, "Meta dcCreator", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.AUTHOR, "Meta author", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.ROBOTS, "Meta robots", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.LANGUAGE, "Meta language", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.CREATED, "Meta created", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.MODIFIED, "Meta modified", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.REVISITAFTER, "Meta revisitAfter", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.DATEPUBLICHCATION, "Meta datePublichcation", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.HOMEPAGE, "Home page", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),

                    stnewEntities(global_const.PAGE_FOOTER, "Nội dung dưới của trang", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.PAGE_FOOTER1, "Nội dung dưới của trang 1", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.PAGE_FOOTER2, "Nội dung dưới của trang 2", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.PAGE_FOOTER3, "Nội dung dưới của trang 3", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.PAGE_FOOTER4, "Nội dung dưới của trang 4", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    ////contact
                    //stnewEntities(global_const.CONTACT, "Thông tin liên hệ", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.CONTACTDETAIL, "Thông tin liên hệ chi tiết", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //support
                    stnewEntities(global_const.SUPPORT, "Hỗ trợ", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.YAHOO, "Hỗ trợ yahoo", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    stnewEntities(global_const.SKYPER, "Hỗ trợ skyper", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                    ////about
                    //stnewEntities(global_const.ABOUT_HOME, "Giới thiệu - trang chủ", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.ABOUT_SHORT, "Giới thiệu - ngắn", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.ABOUT_CONTENT, "Giới thiệu - chi tiết", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0),
                    //stnewEntities(global_const.PRODUCT_CONTENT, "Sản phẩm giới thiệu", (int)admin_const.SETTING_TYPE.TEXT_EDITOR,0)
                    stnewEntities(global_const.ORDER_CODE, "Mã order", (int)admin_const.SETTING_TYPE.TEXT_BOX,1),
                };
        }
        #endregion
        //------------------------------------
        //config_email PAGE
        //------------------------------------
        #region config_email PAGE
        public ActionResult config_email()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult ctr_cf_email_edit(int? id)
        {
            var item_view = new ViewModels.SiteSettingEmailConfigViewModels()
            {
                smtphost = siteSettingModels.getValueByID(global_const.SMTPHOST, admin_const.NO_LANGUAGE),
                smtpport = siteSettingModels.getValueByID(global_const.SMTPPORT, admin_const.NO_LANGUAGE),
                smtpuser = siteSettingModels.getValueByID(global_const.SMTPUSER, admin_const.NO_LANGUAGE),
                smtppass = siteSettingModels.getValueByID(global_const.SMTPPASS, admin_const.NO_LANGUAGE),
                email = siteSettingModels.getValueByID(global_const.EMAIL, admin_const.NO_LANGUAGE)
            };

            return PartialView("../Shared/site_setting/email_config", item_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult ctr_cf_email_edit(FormCollection collection)
        {
            var item_view = new ViewModels.SiteSettingEmailConfigViewModels();
            TryUpdateModel(item_view);

            var lstSetting = new List<site_settings>(){
                CreateItem(global_const.SMTPHOST, item_view.smtphost, admin_const.NO_LANGUAGE,1),
                CreateItem(global_const.SMTPPORT, item_view.smtpport, admin_const.NO_LANGUAGE,1),
                CreateItem(global_const.SMTPUSER, item_view.smtpuser, admin_const.NO_LANGUAGE,1),
                CreateItem(global_const.SMTPPASS, item_view.smtppass, admin_const.NO_LANGUAGE,1),
                CreateItem(global_const.EMAIL, item_view.email,  admin_const.NO_LANGUAGE,1)
            };
            int ret_id = 0;
            foreach (var it in lstSetting)
            {
                ret_id = siteSettingModels.adm_setting_update(it);
            }

            if (ret_id > 0)
            {
                ViewBag.result_message = admin_const.UPDATE_OK;
                ViewBag.redirect = "/vi/admSiteSetting/config_email";
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                ViewBag.result_message = admin_const.UPDATE_FAIL;
                ViewBag.result = false;
                return PartialView("../Shared/site_setting/email_config", item_view);
            }
        }
        #endregion
        //------------------------------------
        //config_storage PAGE
        //------------------------------------
        #region config_storage PAGE
        public ActionResult config_storage()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult ctr_cf_storage_edit(int? id)
        {
            var item_view = new ViewModels.SiteSettingStorageConfigViewModels()
            {
                website_url = siteSettingModels.getValueByID(global_const.WEBSITE_URL, admin_const.NO_LANGUAGE),
                storage_file = siteSettingModels.getValueByID(global_const.STORAGE_CONFIG, admin_const.NO_LANGUAGE),
                server_mappath = System.Web.HttpContext.Current.Server.MapPath("/"),
                server_fullpath = Path.GetFullPath(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("/").ToString()))
            };

            return PartialView("../Shared/site_setting/storage_config", item_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult ctr_cf_storage_edit(FormCollection collection)
        {
            var item_view = new ViewModels.SiteSettingStorageConfigViewModels();
            TryUpdateModel(item_view);

            var lstSetting = new List<site_settings>(){
                CreateItem(global_const.STORAGE_CONFIG, item_view.storage_file, admin_const.NO_LANGUAGE,0),
                CreateItem(global_const.WEBSITE_URL, item_view.website_url, admin_const.NO_LANGUAGE,1)
            };
            int ret_id = 0;
            foreach (var it in lstSetting)
            {
                ret_id = siteSettingModels.adm_setting_update(it);
                if (ret_id > 0)
                {
                    //update single item config
                    siteSettingSingleModels.UpdateConfig(it.setting_name, it.setting_content);
                }
            }

            if (ret_id > 0)
            {
                ViewBag.result_message = admin_const.UPDATE_OK;
                ViewBag.redirect = "/vi/admSiteSetting/config_storage";
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                ViewBag.result_message = admin_const.UPDATE_FAIL;
                ViewBag.result = false;
                return PartialView("../Shared/site_setting/storage_config", item_view);
            }
        }
        #endregion
        //------------------------------------
        //config_list PAGE
        //------------------------------------
        #region config_list PAGE

        public ActionResult config_list()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult ctr_cf_list()
        {
            var page_view = new ViewModels.SiteSettingListViewModels()
            {
                list_settings = ListCommonSetting()
            };
            //save config to file
            var save_config = Request.Form["save_config"];
            if (!string.IsNullOrEmpty(save_config)) {
                //noi luu tru file
                try
                {
                    var sfolder = siteSettingModels.getValueByID(global_const.STORAGE_CONFIG, admin_const.NO_LANGUAGE);
                    if (!string.IsNullOrEmpty(sfolder))
                    {
                        sfolder += Path.DirectorySeparatorChar + global_const.STORAGE_FOLDER + Path.DirectorySeparatorChar;
                        var lstLang = languageModels.get_list_language();
                        foreach (var lang in lstLang)
                        {
                            string cf_file = sfolder + string.Format(global_const.STORAGE_SETTING_FILE, lang.language_code);
                            var dic = siteSettingModels.get_list_config(lang.language_id);
                            Uconfig.CreateConfigFile(dic, cf_file);
                        }
                        ViewBag.result_message = admin_const.UPDATE_OK;
                    }
                    else
                    {
                        ViewBag.result_message = "Chưa thiết lập nơi lưu file config";
                    }
                }
                catch (Exception ex) {
                    ViewBag.result_message += "<br>" + ex.Message;
                }

            }
            if (ViewBag.result_message != null)
                ViewBag.result = true;

            return PartialView("../Shared/site_setting/list_config", page_view);
        }
        #endregion

        //------------------------------------
        //config_edit PAGE
        //------------------------------------
        #region config_edit PAGE
        public ActionResult config_edit()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult ctr_cf_edit(string id)
        {
            if (string.IsNullOrEmpty(id))// || string.IsNullOrEmpty(type))
            {
                ViewBag.redirect = "/vi/admSiteSetting/config_list";
                return PartialView("../Shared/control_redirect");
            }
            var list_langague = languageModels.get_list_language();
            var list_items = new List<data.entities.site_settings>();
            foreach (var it in list_langague)
            {
                var sitem = siteSettingModels.getByID(id, it.language_id);
                sitem.language_id = it.language_id;
                // sitem.setting_type = Convert.ToInt16(type);
                list_items.Add(sitem);
            }
            //lay gia tri thiet lap tu list setting
            var str_desc = "";
            var itype = (int)admin_const.SETTING_TYPE.TEXT_BOX;
            var isconfig = admin_const.DEFAULT_ITEM_STATUS;
            var list_st = ListCommonSetting();
            foreach (var st in list_st)
            {
                if (st.key.ToLower() == id.Trim().ToLower())
                {
                    str_desc = st.desc;
                    itype = st.setting_type;
                    isconfig = st.is_config;
                }
            }
            //tra ve view
            var item_view = new SiteSettingViewModels()
            {
                setting_name = id,
                listLanguage = list_langague,
                setting_type = Convert.ToInt16(itype),
                setting_desc = str_desc,
                listItems = list_items,
                is_config = isconfig
            };

            return PartialView("../Shared/site_setting/edit_config", item_view);
        }

        [ChildActionOnly]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult ctr_cf_edit(FormCollection collection)
        {
            var item_view = new ViewModels.SiteSettingViewModels();
            TryUpdateModel(item_view);
            if (string.IsNullOrEmpty(item_view.setting_name))
            {
                ViewBag.result_message = "Không tìm thấy thiết lập. Hãy trở về trang trước và thao tác lại.";
                ViewBag.result = false;
                return PartialView("../Shared/site_setting/edit_config", item_view);
            }
            //xoa ban ghi de trong- gan gia tri
            for (int i = 0; i < item_view.listItems.Count; i++)
            {
                var itm = item_view.listItems[i];
                if (string.IsNullOrEmpty(itm.setting_content))
                {
                    var lid = itm.language_id;
                    //remove from db
                    siteSettingModels.deleteSetting(item_view.setting_name, lid);
                    //remove from list
                    item_view.listItems.RemoveAt(i);
                }
                else
                {
                    itm.setting_name = item_view.setting_name;
                    itm.is_config = item_view.is_config;
                   // itm.setting_type = item_view.setting_type;
                    itm.date_modified = Udate_time.GetCurrentDateTime();
                    //update db
                    siteSettingModels.adm_setting_update(itm);
                }
            }
            if (item_view.listItems.Count < 0)
            {
                ViewBag.result_message = "Hãy nhập thông tin cấu hình.";
                ViewBag.result = false;
                return PartialView("../Shared/site_setting/edit_config", item_view);
            }

            //foreach(var it in item_view.listItems)
            //      siteSettingModels.adm_setting_update(it);

            ViewBag.result_message = admin_const.UPDATE_OK;
            ViewBag.redirect = "/vi/admSiteSetting/config_list";
            return PartialView("../Shared/control_redirect");
        }
        #endregion

    }
}